package handlers

import (
	"net/http"
	"qcoder_reader/config"
	"qcoder_reader/utils"

	"github.com/gin-gonic/gin"
)

type ConsulConfigRequest struct {
	Host   string `json:"host" binding:"required"`
	Port   int    `json:"port" binding:"required"`
	Scheme string `json:"scheme" binding:"required"`
}

// 获取当前Consul配置
func GetConsulConfig(c *gin.Context) {
	currentConfig := config.AppConfig.Consul
	c.JSON(http.StatusOK, currentConfig)
}

// 更新Consul配置
func UpdateConsulConfig(c *gin.Context) {
	var req ConsulConfigRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 更新全局配置
	config.AppConfig.Consul.Host = req.Host
	config.AppConfig.Consul.Port = req.Port
	config.AppConfig.Consul.Scheme = req.Scheme

	// 保存到配置文件
	if err := config.SaveConfig(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save config: " + err.Error()})
		return
	}

	// 重新初始化Consul连接
	if err := utils.InitConsul(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reinitialize Consul: " + err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Consul配置更新成功"})
}
